package com.nineclock.auth.processor;

import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.auth.exception.NcOAuth2Exception;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.PhoneNumCheckUtils;
import com.nineclock.model.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {
    @Autowired
    private SysUserFeign sysUserFeign;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    RedisTemplate<String,String> redisTemplate;


    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        //手机号  验证码
        String mobile = entity.getAuthParameter("mobile");
        String validateCode = entity.getAuthParameter("password");
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(validateCode)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        if (!PhoneNumCheckUtils.isPhoneLegal(mobile)) {
            throw new NcOAuth2Exception(ResponseEnum.INVALID_PHONE_NUMBER.getMessage());
        }

        String realCode = redisTemplate.boundValueOps(SMSConstant.SMS_LOGIN_KEY_PREFIX + mobile).get();

        if (StringUtils.isEmpty(realCode)||!realCode.equals(validateCode)){
            throw new NcOAuth2Exception(ResponseEnum.INVALID_VERIFY_CODE.getMessage());
        }


        SysUserDTO userDTO = sysUserFeign.queryUser(mobile).getData();
        if (userDTO==null) {
            throw new NcOAuth2Exception(ResponseEnum.INVALID_USERNAME_PASSWORD.getMessage());
        }
        userDTO.setPassword(passwordEncoder.encode(realCode));
        return userDTO;
    }

    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if (entity!=null&&entity.getAuthType()!=null&&entity.getAuthType().equalsIgnoreCase("sms")) {
            return true;
        }
        return false;
    }
}